<?php

namespace WebApp\wx;

class WechatUtil
{
    //验证签名
    public function valid()
    {
        $echoStr = $this->getArr["echostr"];
        $signature = $this->getArr["signature"];
        $timestamp = $this->getArr["timestamp"];
        $nonce = $this->getArr["nonce"];
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }

    //响应消息
    public function responseMsg()
    {
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)){
//            $this->logger("R \r\n".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);

//            var_dump($postObj);exit;
            //消息类型分离
            $result = "";
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                    break;
                case "text":
                    $result = $this->receiveText($postObj);
                    break;
                case "image":
                    //$result = $this->receiveImage($postObj);
                    break;
                case "location":
                    //$result = $this->receiveLocation($postObj);
                    break;
                case "voice":
                    //$result = $this->receiveVoice($postObj);
                    break;
                case "video":
                case "shortvideo":
                    //$result = $this->receiveVideo($postObj);
                    break;
                case "link":
                    //$result = $this->receiveLink($postObj);
                    break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
//            $this->logger("T \r\n".$result);
            echo $result;//xml
        }else {
            echo "000";
            exit;
        }
    }

    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $count = (new UserModel())->get_obj_count(null) + 394;
                $des = "我们只想专注剪好发，剪出你的范儿。\n门店全程互联网运营，服务真实点评，信息公开透明。\n您是本店第{$count}位用户！\n\n-----------温馨提示-----------\n①门店提供茶水，欢迎自助取用\n②门店WIFI密码：jufan123\n";
                $content[] = array("Title" => "欢迎体验 剪约派", "Description" => $des, "Url" => BarberUtil::DOMAIN . "src/view/barber/index.php");

                $openid = $object->FromUserName;
                $userObj = (new UserModel())->get_obj(['openid' => $openid]);
                if ($userObj) {
                    $uid = $userObj['id'];
                    (new UserModel())->update(['state' => 0], ['id' => $uid]);
                }

                //当用户还未关注公众号时, 判断用户是否参加了扫码领卷活动
                $eventKey = $object->EventKey;
                if (isset($eventKey) && strpos($eventKey . "", "qrscene_direct_") !== false) {
                    $des = "欢迎参加领卷活动, 点击领取属于您的优惠卷!" . $eventKey;
                    $content[] = array("Title" => "欢迎参加领卷活动", "Description" => $des, "Url" => "https://www.jianyuepai.com.cn/wx_cp/api/user/login.php?clientType=wx&redirect=https://www.jianyuepai.com.cn/wx_cp/api/user/setActivityTicket.php?activityStrategy=" . $eventKey);
                }
                break;
            case "unsubscribe":
                $content = "取消关注";
                $openid = $object->FromUserName;
                $userObj = (new UserModel())->get_obj(['openid' => $openid]);
                if ($userObj) {
                    $uid = $userObj['id'];
                    (new UserModel())->update(['state' => 43004], ['id' => $uid]);
                }
                break;
            case "CLICK":
                switch ($object->EventKey){
                    case "V1001_GOOD":
                        $content = array();
                        $openid = $object->FromUserName;
                        $userObj = (new UserModel())->get_obj(['openid'=>$openid]);
                        if(!$userObj){
                            $content[] = array("Title"=>"剪约派", "Description"=>"请先关注", "Url" =>BarberUtil::DOMAIN."src/view/barber/index.php");
                        }else{
                            $uid = $userObj['id'];
                            //得到自己最新的order
                            $orderModel = new OrderModel();
                            $TodayOrderObjArr = $orderModel->get_obj_arr(['uid' => $uid, 'create_time' => ['>', date("Y-m-d") . ' 00:00:00'], 'state' => ['!=', 3]], null, 'id', [0, 3]);

                            if (true) {
                                $tempCreateTime = date("Y-m-d") . ' 00:00:00';
                                $TodayOrderObjArr = $orderModel->get_wait_order_data_arr($uid, $tempCreateTime);
                            }

                            $foot = "\n-------------温馨提示-------------\n①门店提供茶水，欢迎自助取用\n②门店WIFI密码：jufan123";
                            $des = "";

                            $TotalOrder = count($TodayOrderObjArr);
                            if($TotalOrder == 0){
                                $des = "还没开始取号排队，亲！\n";
                            }else{
                                $index = 0;
                                foreach($TodayOrderObjArr as $EachOrder){
                                    $barberObj = (new BarberModel())->get_obj(['id'=>$EachOrder['bid']],['name']);
                                    $studioName = (new StudioModel())->get_obj(['owner_id'=>$EachOrder['sid']],['name'])['name'];

                                    if($EachOrder['state'] == BarberUtil::ORDER_STATE_ASKING){
                                        $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n已经到您了！请跟发型师联系！\n";
                                    }else if($EachOrder['state'] == BarberUtil::ORDER_STATE_WAIT){
                                        $count_time_min = BarberUtil::getInstance()->get_remain_time_by_order_id($orderModel, $EachOrder['id']);
                                        if($count_time_min[0] == 0){
                                            $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n已经到您了，请与发型师联系！\n";
                                        }else{
                                            $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n前面还有：{$count_time_min[0]}人\n预计等待时间：约{$count_time_min[1]}(仅供参考)\n";
                                        }
                                    }else if($EachOrder['state'] == BarberUtil::ORDER_STATE_CUTTING){
                                        $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n发型师正在给您服务\n";
                                    }else if($EachOrder['state'] == BarberUtil::ORDER_STATE_SUCCESS){
                                        $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n已经支付完成\n";
                                    }else if($EachOrder['state'] == BarberUtil::ORDER_STATE_CANCEL){
                                        $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n已取消排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n";
                                    }else if($EachOrder['state'] == BarberUtil::ORDER_STATE_UNPAY){
                                        $des = $des."店名：$studioName\n发型师：{$barberObj['name']}\n排号：{$EachOrder['name']}\n取号时间：{$EachOrder['create_time']}\n等待支付\n";
                                    }else{

                                    }

                                    $index++;
                                    if($index < $TotalOrder){
                                        $des = $des."----------------------------------\n";
                                    }
                                }
                            }

                            $des = $des.$foot;

                            $content[] = array("Title"=>"排队进度", "Description"=>$des, "Url" =>BarberUtil::DOMAIN."src/view/barber/index.php?hash=orderlist");
                        }
                        break;
                    case 'FIRST_CUT':
                        $content = array();
                        $openid = $object->FromUserName;
                        $userObj = (new UserModel())->get_obj(['openid'=>$openid]);
                        if(!$userObj){
                            $content[] = array("Title"=>"剪约派", "Description"=>"请先关注", "Url" =>BarberUtil::DOMAIN."src/view/barber/index.php");
                        }else{
                            $app = new CliApp();
                            $app->getRequest()->get['r'] = 'barber/get_ticket';
                            $app->getRequest()->post[Api::ID] = 7;
                            $app->setSESSION([
                                'Barber-openid'=>$userObj['openid'],
                                'Barber-id'=>$userObj['id'],
                            ]);
                            $des="领取成功!\n";
                            try{
                                $app->run();
                            }catch(Exception $e){
                                $json = $e->getMessage();
                                $arr = json_decode($json,1);
                                if($arr[Api::CODE]!==0){
                                    $des = $arr[Api::MESSAGE]."\n";
                                }
                            }
                            $foot = "\n-----------温馨提示-----------\n①门店提供茶水，欢迎自助取用\n②门店WIFI密码：jufan123";
                            $des = $des.$foot;
                            $content[] = array("Title"=>"首单减5元", "Description"=>$des, "Url" =>BarberUtil::DOMAIN."src/view/barber/index.php?hash=mytickets");
                        }
                        break;
                    case "V1001_SHARE_COUNT":
                        $openid = $object->FromUserName;
                        $userObj = (new UserModel())->get_obj(['openid' => $openid]);
                        if (!$userObj) {
                            $content[] = array("Title" => "剪约派", "Description" => "请先关注", "Url" => BarberUtil::DOMAIN . "src/view/barber/index.php");
                        } else {
                            $inviteCount = (new UserModel())->get_obj_count(['invite_user' => $userObj['id']]);
                            $actualInviteObj = (new UserModel())->get_pid_count($userObj['id']);
                            $content = "当前发出邀请: " . $inviteCount . " 人\n" . "当前邀请成功: " . $actualInviteObj['people_count'] . " 人\n" . "获得优惠卷数: " . $actualInviteObj['people_count'] . " 张";
                        }
                        break;
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;
                }
                break;
            case "SCAN":
                //当用户已关注公众号时, 判断用户是否参加了扫码领卷活动
                $eventKey = $object->EventKey;
                if (isset($eventKey) && strpos($eventKey . "", "direct_") !== false) {
                    $des = "欢迎参加领卷活动, 点击领取属于您的优惠卷!";
                    $content[] = array("Title" => "欢迎参加领卷活动", "Description" => $des, "Url" => "https://www.jianyuepai.com.cn/wx_cp/api/user/login.php?clientType=wx&redirect=https://www.jianyuepai.com.cn/wx_cp/api/user/setActivityTicket.php?activityStrategy=" . $eventKey);
                }
                break;

//            case "VIEW":
//                $content = "跳转链接 ".$object->EventKey;
//                break;
//            case "LOCATION":
//                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
//                break;
//            case "scancode_waitmsg":
//                if ($object->ScanCodeInfo->ScanType == "qrcode"){
//                    $content = "扫码带提示：类型 二维码 结果：".$object->ScanCodeInfo->ScanResult;
//                }else if ($object->ScanCodeInfo->ScanType == "barcode"){
//                    $codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
//                    $codeValue = $codeinfo[1];
//                    $content = "扫码带提示：类型 条形码 结果：".$codeValue;
//                }else{
//                    $content = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
//                }
//                break;
//            case "scancode_push":
//                $content = "扫码推事件";
//                break;
//            case "pic_sysphoto":
//                $content = "系统拍照";
//                break;
//            case "pic_weixin":
//                $content = "相册发图：数量 ".$object->SendPicsInfo->Count;
//                break;
//            case "pic_photo_or_album":
//                $content = "拍照或者相册：数量 ".$object->SendPicsInfo->Count;
//                break;
//            case "location_select":
//                $content = "发送位置：标签 ".$object->SendLocationInfo->Label;
//                break;
            default:
//                $content = "receive a new event: ".$object->Event;
                break;
        }

        if(is_array($content)){
            $result = $this->transmitNews($object, $content);
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
//        //多客服人工回复模式
//        if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){
//            $result = $this->transmitService($object);
//            return $result;
//        }

//        //自动回复模式
//        if (strstr($keyword, "文本")){
//            $content = "这是个文本消息";
//        }else if (strstr($keyword, "表情")){
//            $content = "微笑：/::)\n乒乓：/:oo\n中国：".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌：".$this->bytes_to_emoji(0x1F335);
//        }else if (strstr($keyword, "单图文")){
//            $content = array();
//            $content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//        }else if (strstr($keyword, "图文") || strstr($keyword, "多图文")){
//            $content = array();
//            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
//        }else if (strstr($keyword, "音乐")){
//            $content = array();
//            $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3", "HQMusicUrl"=>"http://mascot-music.stor.sinaapp.com/zxmzf.mp3");
//        }else{
//            $content = date("Y-m-d H:i:s",time())."\n\n".'<a href="http://m.cnblogs.com/?u=txw1958">技术支持 方倍工作室</a>';
//        }
//


        /*if(substr($keyword,0,2) ==='cx'){
            $openid = $object->FromUserName;
            $userModel = new UserModel();
            $userObj = $userModel->get_obj(['openid'=>$openid]);
            if($userObj['role']!=BarberUtil::USER_ROLE_BARBER){
                $content = "你好";
            }else{
                $phone = substr($keyword,2,strlen($keyword)-2);
                if(!isMobileNumber($phone)){
                    $content = "不是电话号码";
                }else{
                    $userObj = $userModel->get_obj(['pre_phone'=>$phone]);
                    if($userObj){
                        $content = $userObj['verification'];
                    }else{
                        $content = '请再次尝试发送';
                    }
                }
            }

        }*/

        /*if (substr($keyword, 0, 2) === '1') {
            $openid = $object->FromUserName;
            $userModel = new UserModel();
            $userObj = $userModel->get_obj(['openid' => $openid]);
            if ($userObj['role'] != BarberUtil::USER_ROLE_BARBER) {
                //$content = "亲，恭喜您获得剪约派感恩大回馈活动礼品资格。凭该资格，活动当天还可享受，30元即可领取269元大礼包，包含价值68元紫砂杯一个，价值68元蓝月亮洗衣液一个，价值98元钻石水晶碗一套并赠送免费剪发券一张。更有千元大礼包等您来抽。名额有限，一年仅此一次，千万不要错过。请回复：“参加活动:您的姓名及手机号”完成预约。如：”参加活动：张三，15812345678”多谢合作。";
                $content = "";
            }
        }*/

        /*if (substr($keyword, 0, 2) === '66') {
            $openid = $object->FromUserName;
            $userModel = new UserModel();
            $userObj = $userModel->get_obj(['openid' => $openid]);
            if ($userObj['role'] != BarberUtil::USER_ROLE_BARBER) {
                $content = "感谢您的好评, 欢迎下次惠顾! 如有需要, 可随时联系我们(●ˇ∀ˇ●)";
            }
        }*/

        if (substr($keyword, 0, 3) === '666') {
            $openid = $object->FromUserName;
            $userModel = new UserModel();
            $userObj = $userModel->get_obj(['openid' => $openid]);
            if ($userObj['role'] != BarberUtil::USER_ROLE_BARBER) {
                $content = "感谢您的好评, 欢迎下次惠顾! 如有需要, 可随时联系我们(●ˇ∀ˇ●)";
            }
        }

        if (substr($keyword, 0, 3) === '222') {
            $openid = $object->FromUserName;
            $userModel = new UserModel();
            $userObj = $userModel->get_obj(['openid' => $openid]);
            if ($userObj['role'] != BarberUtil::USER_ROLE_BARBER) {
                $content = "非常抱歉给您造成了困扰! 请问您是对什么地方不满意呢 (⊙_⊙)？";
                $orderLastDateObj = $userModel->getDbManager()->get_obj_by_sql("select DATE_FORMAT(create_time,'%Y-%m-%d') as last_date  from ken_order where id = (select max(id) from ken_order where uid = {$userObj['id']} and state = 100)");
                $startTime = $orderLastDateObj['last_date'] . " 03:00:00";
                $orderList = $userModel->getDbManager()->get_obj_arr_by_sql("select id from ken_order where create_time > '{$startTime}' and uid = {$userObj['id']} and state = 100 and fishpond_feedback is null and fishpond_feedback_time is null");
                foreach ($orderList as $order) {
                    $userModel->getDbManager()->execute("update ken_order set fishpond_feedback = '222',fishpond_feedback_time = now() where id = {$order['id']}");
                }
            }
        }

        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }

    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，经度为：".$object->Location_Y."；纬度为：".$object->Location_X."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = "上传视频类型：".$object->MsgType;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;
    }

    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "        <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, isset($item['Title'])?$item['Title']:"",
                isset($item['Description'])?$item['Description']:"",
                isset($item['PicUrl'])?$item['PicUrl']:"",
                isset($item['Url'])?$item['Url']:"");
        }
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>%s</ArticleCount>
    <Articles>
$item_str    </Articles>
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
        if(!is_array($musicArray)){
            return "";
        }
        $itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    </Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[music]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
        <MediaId><![CDATA[%s]]></MediaId>
    </Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[image]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
    </Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[voice]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
    </Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[video]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复多客服消息
    private function transmitService($object)
    {
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复第三方接口消息
    private function relayPart3($url, $rawData)
    {
        $headers = array("Content-Type: text/xml; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //字节转Emoji表情
    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000){       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{                    # 1 byte
            return chr($cp);
        }
    }

    //日志记录
    private function logger($log_content)
    {
        if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
            sae_set_display_errors(false);
            sae_debug($log_content);
            sae_set_display_errors(true);
        }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
            $max_size = 1000000;
            $log_filename = "log.xml";
            if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
            file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
        }
    }

    public $getArr;
}